package classic150;

import java.util.Objects;

/**
 * <h3>leetcode</h3>
 *
 * @author BigFaceCat
 * @date 2023/12/1 20:50
 * @description <p>leetcode14-最长公共前缀-数组-简单题</p>
 */
public class No14 {
    public static void main(String[] args) {
        String[] strs = {"dog","racecar","car"};
        System.out.println(longestCommonPrefix(strs));
    }

    /**
     * 找到strs里长度最小的字符串，用它的每个字符去比较
     * @param strs
     * @return
     */
    public static String longestCommonPrefix(String[] strs) {
        String temp = strs[0];

        for (int i = 0; i < strs.length; i++) {
            temp = strs[i].length() < temp.length() ? strs[i] : temp;
        }
        char[] chars = temp.toCharArray();

        for (int i = 0; i < chars.length; i++) {
            for (int j = 0; j < strs.length; j++) {
                if (!Objects.equals(strs[j].charAt(i), chars[i])){
                    return i > 0 ? strs[0].substring(0, i) : "";
                }
            }

        }
        return temp;
    }
}